<template>
  <div class="works-compile">
    <!-- head -->
    <qy-navigations
    btnType="normal"
    :tabFunList="tabFunList"
    @publishEssay='publishEssay'
    ></qy-navigations>
    <!-- content -->
    <div class="content">
      <el-form
        ref="form"
        label-width="80px"
        v-for="(item, index) in formData"
        :key="index"
        size="small"
      >
        <!-- title -->
        <div class="title" v-if="item.title">{{ item.title }}</div>
        <div
          class="box_title"
          v-if="index == 'jobExp' || index == 'projectExp'"
        >
          <div class="title">{{ item[0].name.title }}</div>
          <div>
            <i
              class="el-icon-circle-plus-outline"
              @click="controller('add', index)"
            ></i>
          </div>
        </div>
        <!-- input -->
        <el-form-item :label="item.label" v-if="item.mold == 'input'">
          <el-input
            v-model="item.value"
            :placeholder="item.showMsg + item.msg"
          ></el-input>
        </el-form-item>
        <!-- select -->
        <el-form-item :label="item.label" v-if="item.mold == 'select'">
          <el-select
            v-model="item.value"
            :placeholder="item.showMsg + item.msg"
          >
            <el-option
              v-for="(item_select, index_select) in selectOption[item.name]"
              :key="index_select"
              :label="item_select.label"
              :value="item_select.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- textarea -->
        <el-form-item
          :label="item.label"
          prop="desc"
          v-if="item.mold == 'textarea'"
        >
          <el-input
            type="textarea"
            v-model="item.value"
            :placeholder="item.showMsg + item.msg"
          ></el-input>
        </el-form-item>
        <!-- 多组添加 -->
        <div v-if="index == 'jobExp' || index == 'projectExp'" >
          <!-- 循环一 -->
          <div v-for="(item_job, index_job) in item" :key="index_job">
            <div class="box_title_second">
              <div class="title_second">
                <i class="el-icon-tickets" ></i> {{ item_job.name.title }}{{ index_job + 1 }}
              </div>
              <div>
                <i
                  class="el-icon-delete"
                  v-if="index_job > 0"
                  @click="controller('delete', index, index_job)"
                ></i>
              </div>
            </div>
            <!-- 循环二 -->
            <div
              v-for="(item_job_in, index_job_in) in item_job"
              :key="index_job_in"
            >
              <!-- input -->
              <el-form-item
                :label="item_job_in.label"
                v-if="item_job_in.mold == 'input'"
              >
                <el-input
                  v-model="item_job_in.value"
                  :placeholder="item_job_in.showMsg + item_job_in.msg"
                ></el-input>
              </el-form-item>
              <!-- textarea -->
              <el-form-item
                :label="item_job_in.label"
                prop="desc"
                v-if="item_job_in.mold == 'textarea'"
              >
                <el-input
                  type="textarea"
                  v-model="item_job_in.value"
                  :placeholder="item_job_in.showMsg + item_job_in.msg"
                ></el-input>
              </el-form-item>
              <!-- time -->
              <el-form-item
                :label="item_job_in.label"
                v-if="item_job_in.mold == 'time'"
              >
                <el-col :span="11">
                  <el-date-picker
                    type="date"
                    :placeholder="item_job_in.showMsg + item_job_in.msg"
                    v-model="item_job_in.value"
                    style="width: 100%"
                  ></el-date-picker>
                </el-col>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  reactive,
  toRefs,
  onMounted,
  inject
} from "vue";
import formData from "@/views/PersonSpace/assets/compileData.js";
import { ElMessage,ElNotification } from 'element-plus'
import { useRouter, useRoute } from "vue-router"
export default {
  name: "personspaceResumeCompile",
  setup(){
     const state = reactive({
        //Fun列表
        tabFunList:[
          {name:'发布',type:'func',func:'publishEssay',path:''}
        ],
        /* 参数 */
        id:'',
        type:'',
        formData: formData,
        selectOption: {
          sex: [
            { label: "男", value: "男" },
            { label: "女", value: "女" },
          ],
        }
     })
     const Request = inject("$Request")
     const Api = inject("$Api")
     const router = useRouter()
     const route = useRoute()
     // 时间格式转化
     const timeFormat = (date)=> {
        if (date && date != "") {
          const nowdate = date.toLocaleDateString().replace(/\//g, "-");
          return nowdate;
        }
     }
     // 定义一个深拷贝函数  接收目标target参数（递归方式）
     const deepClone = (target) => {
      // 定义一个变量
      let result;
      // 如果当前需要深拷贝的是一个对象的话
      if (typeof target === "object") {
        // 如果是一个数组的话
        if (Array.isArray(target)) {
          result = []; // 将result赋值为一个数组，并且执行遍历
          for (const i in target) {
            // 递归克隆数组中的每一项
            result.push(deepClone(target[i]));
          }
          // 判断如果当前的值是null的话；直接赋值为null
        } else if (target === null) {
          result = null;
          // 判断如果当前的值是一个RegExp对象的话，直接赋值
        } else if (target.constructor === RegExp) {
          result = target;
        } else {
          // 否则是普通对象，直接for in循环，递归赋值对象的所有值
          result = {};
          for (const i in target) {
            result[i] = deepClone(target[i]);
          }
        }
        // 如果不是对象的话，就是基本数据类型，那么直接赋值
      } else {
        result = target;
      }
      // 返回最终结果
      return result;
     }
     //获取初始数据
     const getInitData = (id) => {
        const params = {
          id: id
        };
        Request.requestPost(params, Api.apiPersonSpace.resumeList)
          .then((res) => {
            console.log(res);
            const resData = res.data.data
            for(const item in state.formData){
              if(item != 'jobExp'&&item != 'projectExp'){
                state.formData[item].value = resData[item]
              }
            }
            const jobExpData = resData.jobExp
              jobExpData.map((item,indexs)=>{
                const jobExpDemo = {
                name:{title:'工作经历',name: 'name', value:'',label: '工作地点', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'input', type: '', maxlength: '', msg: '工作地点', errorMsg: "请填写", showMsg: '请填写' },
                content:{name: 'content', value:'',label: '工作内容', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'textarea', type: '', maxlength: '', msg: '工作内容', errorMsg: "请填写", showMsg: '请填写' },
                startTime:{name: 'startTime', value:'',label: '开始时间', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'time', type: '', maxlength: '', msg: '开始时间', errorMsg: "请填写", showMsg: '请填写' },
                endTime:{name: 'endTime', value:'',label: '结束时间', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'time', type: '', maxlength: '', msg: '结束时间', errorMsg: "请填写", showMsg: '请填写' },
              }
              for(const items in jobExpDemo){
                jobExpDemo[items].value = item[items]
              }
              state.formData.jobExp.push(jobExpDemo)
            })
            const projectExpData = resData.projectExp
              projectExpData.map((item,indexs)=>{
                const projectExpDemo = {
                  name:{title:'项目经历',name: 'name', value:'',label: '工作地点', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'input', type: '', maxlength: '', msg: '工作地点', errorMsg: "请填写", showMsg: '请填写' },
                  title:{name: 'title', value:'',label: '项目名称', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'input', type: '', maxlength: '', msg: '项目名称', errorMsg: "请填写", showMsg: '请填写' },
                  content:{name: 'content', value:'',label: '项目内容', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'textarea', type: '', maxlength: '', msg: '项目内容', errorMsg: "请填写", showMsg: '请填写' },
                  startTime:{name: 'startTime', value:'',label: '开始时间', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'time', type: '', maxlength: '', msg: '开始时间', errorMsg: "请填写", showMsg: '请填写' },
                  endTime:{name: 'endTime', value:'',label: '结束时间', checkRule: /^[\s\S]*.*[^\s][\s\S]*$/, mold: 'time', type: '', maxlength: '', msg: '结束时间', errorMsg: "请填写", showMsg: '请填写' },
                }
                for(const items in projectExpDemo){
                  projectExpDemo[items].value = item[items]
                }
                state.formData.projectExp.push(projectExpDemo)
              })
              if(state.formData.jobExp.length>1){
                state.formData.jobExp.splice(0,1)
              }
              if(state.formData.projectExp.length>1){
                state.formData.projectExp.splice(0,1)
              }
              console.log('返回编辑数据',state.formData)
          })
          .catch((err) => {
            console.error(err);
          });
     }
     const submitData = (data)=> {
        const params = data;
        Request.requestPost(params,Api.apiPersonSpace.resumeAdd)
          .then((res) => {
            console.log(res);
            ElMessage({
              message: "success",
              center: true,
            });
            setTimeout(() => {
              router.push("/personspace/resume");
            }, 1000);
          })
          .catch((err) => {
            console.error(err);
          });
    }
    // compile data
    const compileData = (data) => {
      const params = data;
      Request.requestPost(params, Api.apiPersonSpace.resumeCompile)
        .then((res) => {
          console.log(res);
          ElMessage({
            message: "success",
            center: true,
          });
          setTimeout(() => {
            //跳转初始化formdata数据
            router.replace({path:'/personspace/resume'})
          }, 1000);
        })
        .catch((err) => {
          console.error(err);
        });
    }
    //发布文章
    const publishEssay = () => {
      if(state.type == 'add'){
        //时间格式转化
        state.formData.jobExp.map((item) => {
          item.startTime.value = timeFormat(item.startTime.value);
          item.endTime.value = timeFormat(item.endTime.value);
        });
        state.formData.projectExp.map((item) => {
          item.startTime.value = timeFormat(item.startTime.value);
          item.endTime.value = timeFormat(item.endTime.value);
        });
      }
      //数据深拷贝
      const data = deepClone(state.formData);
      console.log("提交数据", data);
      for (const item in data) {
        if (item == "jobExp" || item == "projectExp") {
          data[item].map((itemA, index) => {
            for (const itemB in itemA) {
              itemA[itemB] = itemA[itemB].value;
            }
          });
        } else {
          data[item] = data[item].value;
        }
      }
      data.jobExp = JSON.stringify(data.jobExp);
      data.projectExp = JSON.stringify(data.projectExp);
      if(state.type == 'add'){
          submitData(data);
      }else if(state.type == 'compile'){
          compileData(Object.assign(data,{id:state.id}));
      }  
      console.log("结果", data);
      console.log("原型结果", state.formData);
    }

    // controller
    const controller = (name, index, id) => {
      switch (name) {
        case "add":{
          const jobExpItem = {
            name: {
              title: "工作经历",
              name: "name",
              label: "工作地点",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "input",
              type: "",
              maxlength: "",
              msg: "工作地点",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            content: {
              name: "content",
              label: "工作内容",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "textarea",
              type: "",
              maxlength: "",
              msg: "工作内容",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            startTime: {
              name: "startTime",
              label: "开始时间",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "time",
              type: "",
              maxlength: "",
              msg: "开始时间",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            endTime: {
              name: "endTime",
              label: "结束时间",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "time",
              type: "",
              maxlength: "",
              msg: "结束时间",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
          };
          const projectExpItem = {
            name: {
              title: "项目经历",
              name: "name",
              label: "工作地点",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "input",
              type: "",
              maxlength: "",
              msg: "工作地点",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            title: {
              name: "title",
              label: "项目名称",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "input",
              type: "",
              maxlength: "",
              msg: "项目名称",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            content: {
              name: "content",
              label: "项目内容",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "textarea",
              type: "",
              maxlength: "",
              msg: "项目内容",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            startTime: {
              name: "startTime",
              label: "开始时间",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "time",
              type: "",
              maxlength: "",
              msg: "开始时间",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
            endTime: {
              name: "endTime",
              label: "结束时间",
              checkRule: /^[\s\S]*.*[^\s][\s\S]*$/,
              mold: "time",
              type: "",
              maxlength: "",
              msg: "结束时间",
              errorMsg: "请填写",
              showMsg: "请填写",
            },
          };
          ElNotification({
            title: "成功",
            message: "添加成功",
            type: "success",
            duration: 1000,
          });
          if (index == "jobExp") {
            state.formData.jobExp.push(jobExpItem);
          } else if (index == "projectExp") {
            state.formData.projectExp.push(projectExpItem);
          }
          break;
        }
        case "delete":{
          ElNotification({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 1000,
          });
          if (index == "jobExp") {
            state.formData.jobExp.splice(id, 1);
          } else if (index == "projectExp") {
            state.formData.projectExp.splice(id, 1);
          }
        }
        break;
        case "submit":{
          if(state.type == 'add'){
            //时间格式转化
            state.formData.jobExp.map((item) => {
              item.startTime.value = timeFormat(item.startTime.value);
              item.endTime.value = timeFormat(item.endTime.value);
            });
            state.formData.projectExp.map((item) => {
              item.startTime.value = timeFormat(item.startTime.value);
              item.endTime.value = timeFormat(item.endTime.value);
            });
          }
          //数据深拷贝
          const data = deepClone(state.formData);
          console.log("提交数据", data);
          for (const item in data) {
            if (item == "jobExp" || item == "projectExp") {
              data[item].map((itemA, index) => {
                for (const itemB in itemA) {
                  itemA[itemB] = itemA[itemB].value;
                }
              });
            } else {
              data[item] = data[item].value;
            }
          }
          data.jobExp = JSON.stringify(data.jobExp);
          data.projectExp = JSON.stringify(data.projectExp);
          if(state.type == 'add'){
             submitData(data);
          }else if(state.type == 'compile'){
             compileData(Object.assign(data,{id:state.id}));
          }  
          console.log("结果", data);
          console.log("原型结果", state.formData);
          break;
        }
        case "works":
          router.push("/personspace/resume");
          break;
        case "home":
          router.push("/");
          break;
        default:
          break;
      }
    }

    onMounted(() => {
      state.type = route.query.type
      state.id = route.query.id
      if(state.type == 'compile'){
        getInitData(state.id)
        document.title = '编辑简历'
      }else{
        document.title = '添加简历'
      }
    })

    return{
      ...toRefs(state),
      getInitData,
      submitData,
      deepClone,
      publishEssay,
      timeFormat,
      controller
    }
  },
  beforeCreate() {
    document
      .querySelector("body")
      .setAttribute("style", "background-color:rgba(204,204,204,0.2)");
  }
};
</script>

<style scoped lang="scss">
@import "@/styles/variable.scss";
//content
.content {
  width:80vw;
  height: auto;
  margin-left: 10vw;
  margin-top: 100px;
  padding-bottom: 100px;
  text-align: left;
  font-size: 14px;
}
.content .box_title {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.content .title {
  font-size: 14px;
  font-weight: bolder;
  margin-left: 12px;
  padding: 12px 0;
  color: $black-weight;
}
.content .box_title_second {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.content .title_second {
  font-size: 14px;
  font-weight: bolder;
  margin-left: 12px;
  padding: 12px 0;
  color: $black-light;

}
</style>
